package co2.bean;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import co2.engine.DAOInterface;
import co2.engine.SpringUtil;
import co2.pojos.MstUser;

@ManagedBean
@ViewScoped
public class TemplateBean extends AbstractBean implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private boolean loggedIn;
	private String userName;
	
	@Autowired
	@Qualifier("daoI")
	private DAOInterface dao;
	
	
	@PostConstruct
	public void postCon(){
		
		try{
			Map map = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
			if(map!=null && map.get("userId") != null){
				String userId = map.get("userId").toString();
				MstUser user = (MstUser) dao.get(MstUser.class, userId);
				loggedIn = true;
				userName = user.getUsername();
			}else{
				loggedIn=false;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void doLogout(){
		try {
			String extUrl=FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();

			FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.invalidate();

			FacesContext.getCurrentInstance().getExternalContext().redirect(extUrl+"/jsf/target/front_ui.jsf");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
	public boolean isLoggedIn() {
		return loggedIn;
	}

	public void setLoggedIn(boolean loggedIn) {
		this.loggedIn = loggedIn;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public DAOInterface getDao() {
		return dao;
	}

	public void setDao(DAOInterface dao) {
		this.dao = dao;
	}
}
